package leetcode_core.leetcode_1;

public class ReverseKGroup {
    public class ListNode {
        int val;
        ListNode next;
        ListNode() {}
        ListNode(int val) { this.val = val; }
        ListNode(int val, ListNode next) { this.val = val; this.next = next; }
    }

    public ListNode reverseKGroup(ListNode head, int k) {
        if(head == null){
            return null;
        }
        ListNode a,b;
        a=b=head;
        for(int i =0;i<k;i++){
            //不足k个,不需要反转,base-case
            if(b==null){
                return head;
            }
            b=b.next;
        }
        //反转前k个元素
        ListNode newHead = reverse(a,b);
        a.next = reverseKGroup(b,k);
        return newHead;
    }

    public ListNode reverse(ListNode a,ListNode b){
        ListNode pre=null,cur=a,next=a;
        while(cur!=b){
            next = cur.next;
            cur.next = pre;
            pre = cur;
            cur=next;
        }
        return pre;
    }

}
